package com.mifengkong.frwidget.banner;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;

import java.lang.ref.WeakReference;


/**
 * user guide, image indicator
 *
 * @author savant-pan
 */
public abstract class AbsIndicatorView extends RelativeLayout {


    protected Handler refreshHandler;

    /**
     * page total count
     */
    protected int totelCount = 0;
    /**
     * current page
     */
    protected int currentIndex = 0;


    public AbsIndicatorView(Context context) {
        this(context, null);
    }

    public AbsIndicatorView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AbsIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    /**
     * @param context
     */
    private void init(Context context) {
        this.refreshHandler = new ScrollIndicateHandler(AbsIndicatorView.this);
        LayoutInflater.from(context).inflate(layoutRes(), this);
        findView();

    }

    protected abstract void findView();

    protected abstract int layoutRes();

    /**
     * get current index
     */
    public int getCurrentIndex() {
        return this.currentIndex;
    }

    /**
     * git view count
     */
    public int getTotalCount() {
        return this.totelCount;
    }

    public void setTotalCount(int size) {
        this.totelCount = size;
    }

    /**
     * set show item current
     *
     * @param index postion
     */
    public void setCurrentItem(int index) {
        this.currentIndex = index;
    }

    /**
     * show
     */
    public abstract void show();

    /**
     * refresh indicate anchor
     */
    protected abstract void refreshIndicateView();

    /**
     * ScrollIndicateHandler
     */
    private static class ScrollIndicateHandler extends Handler {
        private final WeakReference<AbsIndicatorView> scrollIndicateViewRef;

        public ScrollIndicateHandler(AbsIndicatorView scrollIndicateView) {
            this.scrollIndicateViewRef = new WeakReference<AbsIndicatorView>(
                    scrollIndicateView);

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            AbsIndicatorView scrollIndicateView = scrollIndicateViewRef.get();
            if (scrollIndicateView != null) {
                scrollIndicateView.refreshIndicateView();
            }
        }
    }

}
